package com.ruoyi.common.utils.mstnExcel;

import com.univocity.parsers.common.processor.BeanListProcessor;
import com.univocity.parsers.csv.CsvFormat;
import com.univocity.parsers.csv.CsvParser;
import com.univocity.parsers.csv.CsvParserSettings;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;


public class CsvUtils {


    /**
     * 读取crv文件并转换成List
     *
     * @param clazz  bean对象
     * @param file   待读取文件
     * @return crv对象list
     */
    public static <T> List<T> read(MultipartFile file, Class<T> clazz) {
        return read(file, clazz, "utf-8");
    }
    public static <T> List<T> read(MultipartFile file, Class<T> clazz, String charset) {

        List<T> result;
        try {
            BeanListProcessor<T> rowProcessor = new BeanListProcessor<>(clazz);

            InputStream in = file.getInputStream();
//            InputStreamReader reader = new InputStreamReader(in, "GBK");
            InputStreamReader reader = new InputStreamReader(in, charset);

            CsvParserSettings settings = new CsvParserSettings();
            settings.getFormat().setLineSeparator("\n");
            settings.setProcessor(rowProcessor);
            settings.setFormat(new CsvFormat());

            CsvParser parser = new CsvParser(settings);
            parser.parse(reader);
            //逐行读取
            result = rowProcessor.getBeans();
        } catch (Exception e) {
            return null;
        }
        return result;
    }

}
